﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HeqinSjsc2024.Class.Ding
{
    internal class DingCom
    {
        /// <summary>
        /// 发送钉钉文字消息函数
        /// </summary>
        /// <param name="dingToken"></param>
        /// <param name="openConversationId"></param>
        /// <param name="robotCode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string SendDingGroupTextMessage(string dingToken, string openConversationId, string robotCode, string message)
        {
            HttpClient client = new HttpClient();
            var obj = new JObject
                {
                    { "content", message }
                };

            // 转换为 JSON 字符串
            string jsonString = obj.ToString();

            // 构建请求体
            var requestBody = new
            {
                msgParam = jsonString,
                msgKey = "sampleText",
                openConversationId = openConversationId,
                robotCode = robotCode,
            };

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            // 设置请求头
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("x-acs-dingtalk-access-token", dingToken);

            try
            {
                // 发送 POST 请求
                var response = client.PostAsync("https://api.dingtalk.com/v1.0/robot/groupMessages/send", content).Result;

                // 如果请求成功
                if (response.IsSuccessStatusCode)
                {
                    var responseBody = response.Content.ReadAsStringAsync().Result;
                    return responseBody; // 返回响应内容
                }
                else
                {
                    // 处理错误
                    var errorMessage = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine($"Error: {response.StatusCode}, Message: {errorMessage}");
                    return null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
                return null;
            }
        }


    }
}
